﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SharingCenter.Web.Classes;

namespace SharingCenter.Web.Account
{
    using SharingCenter.Web.Classes.enums;
    using SharingCenter.Web.Classes.Accounts;
    using Recaptcha;
    using SharingCenter.Web.Classes.Account;
    using SharingCenter.Web.Classes.Message;
    using SharingCenter.Web.Classes.Profiles;
    using SharingCenter.Web.Classes.Contact;

    public partial class Register : Classes.PageBase
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            CreateUserWizard1.CreatingUser += new LoginCancelEventHandler(CreateUserWizard1_CreatingUser);
            CreateUserWizard1.CreateUserError += new CreateUserErrorEventHandler(CreateUserWizard1_CreateUserError);
            CreateUserWizard1.CreatedUser += new EventHandler(CreateUserWizard1_CreatedUser);
            if (!IsPostBack)
            {
                if (Request.QueryString["ref"] != null)
                {
                    try
                    {
                        Guid refUserId = new Guid(Request.QueryString["ref"]);
                        Sc_Profile refProfile = ProfileOperations.GetProfile(refUserId);
                        if (refProfile != null)
                        {
                            Session["REF_UID"] = refUserId;
                        }
                        else
                        {
                            Session["REF_UID"] = null;
                        }
                    }
                    catch
                    {
                        Session["REF_UID"] = null;
                    }
                }
                else
                {
                    Session["REF_UID"] = null;
                }
            }
        }

        void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
        {
            ////if (!IsUserNameAdmin(CreateUserWizard1.UserName))
            ////{
            ////    aspnet_User u = dataContext.aspnet_Users.Single(d => d.UserName == CreateUserWizard1.UserName);
            ////    InitializeProfile(u);
            ////    InitializeAddress(u);
            ////    InitializePrivacy(u);
            ////    dataContext.SubmitChanges();
            ////    RoleOperations.AddUserToRole(u.UserName, WebsiteRole.User);
            ////}
            ////else
            ////{
            ////    RoleOperations.AddUserToRole(CreateUserWizard1.UserName, WebsiteRole.GeneralAdmin);
            ////}

            
            

            // send activate mail
            string userName = CreateUserWizard1.UserName;
            string email = CreateUserWizard1.Email;
            string password = CreateUserWizard1.Password;
            string activateCode = AccountOperations.GenerateActivateCode(userName);
            HiddenField hdn = (HiddenField)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("hdnNickNameAbb");
            TextBox nickname = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("NickNameText");
            MembershipUser u = Membership.GetUser(userName);
            string fmt = Session["REF_UID"] == null ? "{0}{3}{1}{3}{2}" : "{0}{3}{1}{3}{2}{3}{4}";
            u.Comment = string.Format(fmt, activateCode, hdn.Value, nickname.Text, WebConsts.STR_SEPERATOR[0], Session["REF_UID"] != null ? Session["REF_UID"].ToString() : "");

            bool verifyMail = true;
            try
            {
                verifyMail = SiteConfig.ReadSetting(SiteConfigSection.Account, "VerifyEmail") == "1";
            }
            catch{verifyMail = true;}
            
            if (verifyMail)
            {
                u.IsApproved = false;

                Dictionary<string, string> rep = new Dictionary<string, string>();
                rep.Add("UserName", userName);
                rep.Add("Password", password);
                rep.Add("ActivateLink", string.Format("{0}/Account/Activate.aspx?email={1}&c={2}",
                    WebConsts.SITE_URL,
                    email,
                    activateCode
                    ));
                rep.Add("Email", email);
                bool sent = MailOperations.SendSystemMail("Account", "UserCreated", userName, rep);
                if (!sent)
                {
                    Membership.DeleteUser(userName);
                    SetTopMostMessage("邮件发送错误，注册已取消。", true);
                    RefreshPage();
                }
            }
            else
            {
                if (!ProfileOperations.InitializeProfile(userName, nickname.Text, hdn.Value))
                {
                    Membership.DeleteUser(userName);
                    SetTopMostMessage("初始化账号错误，注册已取消。", true);
                    RefreshPage();
                }
                else
                {
                    // success
                    if (Session["REF_UID"] != null)
                    {
                        Guid refUserId = new Guid(Session["REF_UID"].ToString());
                        Guid userId = WebProfile.GetProfile(email).UserId;
                        ContactOperations.ApproveContact(refUserId, userId, "", true, true);
                        
                    }
                    SetTopMostMessage("注册成功，请登录。", true);
                    Response.Redirect("~/Account/Login.aspx", true);
                }
            }

            Membership.UpdateUser(u);
            Session["REF_UID"] = null;
        }

        

        void CreateUserWizard1_CreateUserError(object sender, CreateUserErrorEventArgs e)
        {
            switch (e.CreateUserError)
            {
                case System.Web.Security.MembershipCreateStatus.DuplicateEmail:
                    break;
                case System.Web.Security.MembershipCreateStatus.InvalidPassword:
                    break;
                default: break;
            }
            
        }

        protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            if (IsValid)
            {
                CreateUserWizard1.UserName = CreateUserWizard1.Email;
                ViewState["RegEmail"] = CreateUserWizard1.Email;
            }
            else
            {
                e.Cancel = true;
                //RecaptchaControl ctrl = (RecaptchaControl)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("RecaptchaControl1");
                
            }
        }

        void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && Request.QueryString["m"] != null)
            {
                CreateUserWizard1.Email = Request.QueryString["m"];
            }
        }

        protected void btnReg_Command(object sender, CommandEventArgs e)
        {
            if (IsPostBack)
            {
                //Shared.ValicationCode v = (Shared.ValicationCode)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("ValidationCode1");
                if (!IsValid)
                {
                    msgWrongCode.Visible = true;
                }
                else
                {
                    msgWrongCode.Visible = false;
                }
            }
        }

        protected void RecaptchaControl1_Init(object sender, EventArgs e)
        {
            
        }
    }
}
